package pf2.pdd.uea;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

public class HistoricoContentProvider extends ContentProvider{
	
	private HistoricoDB hDB;
	
	private static final String AUTHORITY = 
			"pf2.pdd.uea.HistoricoContentProvider";
	private static final String HISTORIC_BASE_PATH = "historic";
	public static final int HISTORIC_CODE = HISTORIC_BASE_PATH.hashCode();
	public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
			+ "/" + HISTORIC_BASE_PATH);
	
	private static final UriMatcher sURIMatcher = new UriMatcher(
			UriMatcher.NO_MATCH);

	static {
		sURIMatcher.addURI(AUTHORITY, HISTORIC_BASE_PATH, HISTORIC_CODE);
	}


	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = hDB.getWritableDatabase();
		
		int count = db.delete(HistoricoDB.TABLE_HISTORIC, selection, selectionArgs);
		
		getContext().getContentResolver().notifyChange(uri, null);
		
		return count;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		
		if (sURIMatcher.match(uri) != HISTORIC_CODE) {
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		
		SQLiteDatabase db = hDB.getWritableDatabase();
		
		long rowId = db.insert(hDB.TABLE_HISTORIC, HistoricoDB.COL_MEDICINE, values);
		
		if (rowId > 0) {
			Uri uriHistoric = ContentUris.withAppendedId(CONTENT_URI, rowId);
			getContext().getContentResolver().notifyChange(uriHistoric, null);
			return uriHistoric;
		}

		return null;
	}

	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		hDB = new HistoricoDB(getContext(), null, 0);
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		// TODO Auto-generated method stub
		
		SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
		
		queryBuilder.setTables(HistoricoDB.TABLE_HISTORIC);
		
		queryBuilder.appendWhere(HistoricoDB.ID + "="
				+ uri.getLastPathSegment());
		
		Cursor cursor = queryBuilder.query(hDB.getReadableDatabase(),
				projection, selection, selectionArgs, null, null, sortOrder);
		
		cursor.setNotificationUri(getContext().getContentResolver(), uri);

		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

}
